import { ActionReducerMapBuilder, Draft } from "@reduxjs/toolkit";
import { AsyncThunk, AsyncThunkConfig } from "@reduxjs/toolkit/dist/createAsyncThunk";
import JsonResult from "http/JsonResult";
import { PagingData, PagingResult } from "type/Page";
import { StatePagingType } from "..";
import RequestStatus from "../RequestStatus";

/**
 * 构建异步分页action的处理器
 * @param builder 异步action构建器
 * @param asyncAction 分页的异步action
 */
export const builderPagingHandler = <T, > (builder: ActionReducerMapBuilder<StatePagingType<T>>, asyncAction: AsyncThunk<JsonResult<PagingResult<T>>, PagingData, AsyncThunkConfig> ) => {
    builder.addCase(asyncAction.pending, (state) => {
        state.requestStatus = RequestStatus.PENDING;
        state.loading = true;
    });
    builder.addCase(asyncAction.rejected, (state) => {
        state.requestStatus = RequestStatus.FAILED;
        state.loading = false;
    });
    builder.addCase(asyncAction.fulfilled, (state, action) => {
        state.requestStatus = RequestStatus.SUCCESS;
        state.loading = false;
        if(action.payload.success){
            const { data, currentPage, pageSize, total } = action.payload.data;
            state.data = data as Draft<T[]>;
            state.total = total;
            state.currentPage = currentPage;
            state.pageSize = pageSize;
        }
    });
};